import React, { useEffect, useState } from 'react';
import { Tabs, TabPaneProps, Button, message } from 'antd';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/cjs/styles/hljs';
import { copy } from '@/app/common/utils';

const { TabPane } = Tabs;

interface TabPanePropsExtend extends TabPaneProps {
  value?: string;
  language?: string;
}

const languageMap = new Map([
  ['java', 'java'],
  ['sql', 'sql'],
  ['js', 'javascript'],
  ['vue', 'javascript'],
  ['jsx', 'jsx'],
  ['xml', 'xml'],
]);

export default function PreViewContent(props: { codeObj: Record<string, any> }) {
  const [tabs, setTabs] = useState<TabPanePropsExtend[]>([]);

  useEffect(() => {
    const panels = [];
    for (const iterator in props.codeObj) {
      const tab = iterator.replace(/vm\/.*\/(.*)\.vm/, '$1');
      let language = '';
      languageMap.forEach((v, k) => {
        const matchReg = tab.match(k);
        if (matchReg !== null && k === matchReg.at(0)) {
          language = v;
        }
      });
      panels.push({
        tab,
        tabKey: tab,
        value: props.codeObj[iterator],
        language,
      });
    }
    setTabs(panels);
  }, [props.codeObj]);

  return (
    <Tabs defaultActiveKey="1">
      {tabs.map(d => {
        return (
          <TabPane style={{ height: '500px', overflow: 'auto' }} tab={d.tab} key={d.tabKey}>
            <Button
              type="link"
              onClick={() => copy(d.value, () => message.success('代码已复制到粘贴板'))}
            >
              复制
            </Button>
            <SyntaxHighlighter showLineNumbers wrapLines language={d.language} style={{ ...dark }}>
              {d.value}
            </SyntaxHighlighter>
          </TabPane>
        );
      })}
    </Tabs>
  );
}
